Inherit methods from a field automatically (via procedural macros).
Motivation
While Rust is partially inspired by the object-oriented programming (OOP) paradigm and has some typical OOP features (like objects, encapsulation, and polymorphism), it is not an OOP language. One piece of evidence is the lack of inheritance, which an important pillar of OOP. But don't take me wrong: this lack of inheritance is actually a good thing since it promotes the practice of composition over inheritance in Rust programs. Despite all the benefits of composition, Rust programmers have to write trivial fowarding methods, which is a tedious task, especially when you have to write many of them.
To address this pain point of using composition in Rust, the crate provides a convenient procedure macro that generates forwarding methods automatically for you. In other words, your structs can now "inherit" methods from their fields, enjoying the best of both worlds: the convenience of inheritance and the flexibility of composition.
Examples
Implementing the new type idiom
Suppose that you want to create a new struct named Stack<T>
, which can be implemented by
simply wrapping around Vec<T>
and exposing only a subset of the APIs of Vec
. Here is
how this crate can help you do it easily.
use inherit_methods;
;
// Annotate an impl block with #[inherit_methods(from = "...")] to enable automatically
// inheriting methods from a field, which is specifiedd by the from attribute.
If you want to derive common traits (like AsRef
and Deref
) for a wrapper type, check out
the shrinkwraprs crate.
Emulating the classic OOP inheritance
In many OOP frameworks or applications, it is useful to have a base class from which all objects
inherit. In this example, we would like to do the same thing, creating a base class
(the Object
trait for the interface and the ObjectBase
struct for the implementation).
that all objects should "inherit".
use ;
use Mutex;
use inherit_methods;